package com.ecode.annotation.core;

import com.ecode.annotation.EcodeDo;
import com.ecode.annotation.ErrorCode;
import com.ecode.annotation.builder.http.HttpCodeDataPullBuilder;
import com.ecode.annotation.builder.local.LocalPathCodeDataPullBuilder;
import com.ecode.annotation.builder.mysql.MysqlCodeDataPullBuilder;
import com.ecode.annotation.builder.proj.ProjectCodeDataPullBuilder;
import com.ecode.annotation.data.json.JsonCodeDataParse;
import com.ecode.annotation.data.text.TextCodeDataParse;
import com.ecode.annotation.model.ErrorCodeDO;

import java.util.Set;

/**
 * @ClassName DefaultErrorCoderBuilder
 * @Author mjlft
 * @Date 2021/9/25 14:25
 * @Version 1.0
 * @Description 错误构建器
 */
public class DefaultErrorCoderBuilder implements ErrorCodeBuilder {

    @Override
    public Set<ErrorCodeDO> parseErrorCode(EcodeDo ecodeDo) {
        CodeDataPullBuilder dataPullBuilder = null;
        switch (ecodeDo.getDataFROM()){
            case MYSQL:
                dataPullBuilder = new MysqlCodeDataPullBuilder();
                break;
            case HTTP:
                dataPullBuilder = new HttpCodeDataPullBuilder();
                break;
            case PROJECT:
                dataPullBuilder = new ProjectCodeDataPullBuilder();
                break;
            case LOCALPATH:
                dataPullBuilder = new LocalPathCodeDataPullBuilder();
                break;
            case OTHER:
                try {
                    dataPullBuilder = (CodeDataPullBuilder) Class.forName(ecodeDo.getCustomDataPullBuilder()).newInstance();
                } catch (Exception e) {
                    throw new RuntimeException("自定义数据拉取构建器实例化失败");
                }
                break;
        }
        if(dataPullBuilder == null){
            throw new RuntimeException("CodeDataPullBuilder 构建器解析失败");
        }

        CodeDataParse codeDataParse = null;
        switch (ecodeDo.getDataType()){
            case JSON:
                codeDataParse = new JsonCodeDataParse();
                break;
            case TEXT:
                codeDataParse = new TextCodeDataParse();
                break;
            case OTHER:
                try {
                    codeDataParse = (CodeDataParse) Class.forName(ecodeDo.getCustomDataParseClass()).newInstance();
                } catch (Exception e) {
                    throw new RuntimeException("自定义数据拉取构建器实例化失败");
                }
                break;
            default:
                throw new RuntimeException("数据配置类型不支持");
        }
        if(codeDataParse == null){
            throw new RuntimeException("数据解析配置类型无效");
        }
        String dataCodeStr =  dataPullBuilder.dataPull(ecodeDo);
        return codeDataParse.parseStrToData(dataCodeStr);
    }

    @Override
    public Set<ErrorCodeDO> parseErrorCode(ErrorCode errorCode) {
        EcodeDo ecodeDo = EcodeDo.buildFromErrorCode(errorCode);
        return parseErrorCode(ecodeDo);
    }
}
